package com.leehom.arch.storage.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leehom.arch.storage.FileUtils;
import com.leehom.arch.storage.exception.FileStorageException;
import com.leehom.arch.storage.exception.MessageCode;
import com.leehom.arch.storage.handler.FileStorageHandler;
import com.leehom.arch.storage.handler.LocalFileStorageHandler;
import com.leehom.arch.storage.model.FileItem;
import com.leehom.arch.storage.model.Storage;
import com.leehom.arch.storage.service.FileService;

import lombok.Data;

/**
 * @类名: FileServiceImpl
 * @说明: 文件服务实现
 *
 * @author   leehom
 * @Date	 2020年12月3日 上午10:36:31
 * 修改记录：
 *
 *   
 * @see 	 
 */
@Data
public class FileServiceImpl implements FileService {
	
	private static final Logger logger = LoggerFactory.getLogger(LocalFileStorageHandler.class);

	private Storage storage;
	
	private FileStorageHandler handler;
	
	@Override
	public InputStream getFile(String path, String fileName) throws FileStorageException {
		return handler.getFile(path, fileName, storage);
	}
	
	@Override
	public InputStream getFileMd5(String path, String fileName, String md5) throws FileStorageException {
		InputStream is = this.getFile(path, fileName);
		try {
			String checkMd5 = FileUtils.checkFileMd5(is);
			if(!md5.equals(checkMd5))
				throw new FileStorageException(MessageCode.ERROR_STORAGE_FILEECHECKFAILURE, FileUtils.contactPath(path, fileName));
			return is;
		} catch (IOException e) {
			throw new FileStorageException(MessageCode.ERROR_STORAGE_FILEECHECKIO, FileUtils.contactPath(path, fileName));
		}

	}

	@Override
	public InputStream getFileSha(String path, String fileName, String sha) throws FileStorageException {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void storeFile(String path, String fileName, File file) throws FileStorageException {
		InputStream is;
		try {
			is = new FileInputStream(file);
			this.storeFile(path, fileName, is);
		} catch (FileNotFoundException e) {
			throw new FileStorageException(MessageCode.ERROR_STORAGE_FILENOTEXISTS, FileUtils.contactPath(path, fileName));
		} finally {
			
		}
		
	}

	@Override
	public void storeFile(String path, String fileName, InputStream is) throws FileStorageException {
		handler.saveFile(path, fileName, is, storage);
	}

	@Override
	public List<FileItem> listFiles(String path) throws FileStorageException {
		return handler.listFileOfDir(path, storage);
	}

	@Override
	public String getUrl(String path, String fileName) throws FileStorageException {
		return handler.getUrl(path, fileName, storage);
	}

}
